import { getCookies } from "./auth";
import { ElMessage } from 'element-plus'
import {newsStore} from '@/store/index.js'
import {formatYMD} from '@/utils/time.js'

// 获取pinia中的实例
const newsMainStore = newsStore()

const user_id = getCookies('user_id')

/**
 * 一系列常量参数
 */
const MESSAGE_REQUEST = 1; //消息请求
 const MESSAGE_RESPONSE = 2; //消息响应
 const CREATE_GROUP_REQUEST = 3; //创建群
 const CREATE_GROUP_RESPONSE = 4; //创建群响应
 const LOGIN_REQUEST = 5; //登录请求
 const LOGIN_RESPONSE = 6; // 登录响应
 const REGISTER_REQUEST = 7;  //注册请求
 const REGISTER_RESPONSE = 8; //注册响应
 const GROUP_MESSAGE_REQUEST = 9;  //发送群消息
 const GROUP_MESSAGE_RESPONSE = 10; //接收群消息
 const HEARTBEAT_REQUEST = 11; //心跳消息请求
 const HEARTBEAT_RESPONSE = 12; //心跳消息恢复

 

let socket = null
let setIntervalWeSocketPush = null
let url = 'ws://152.136.188.204:9999'

/**
 * 建立webSocket连接
 * @param {*} url  ws地址
 */
export const createSocket = () => {
  socket && socket.close()
  if(!socket) {
    socket = new WebSocket(url)
    socket.onopen = onopenWS
    socket.onmessage = onmessageWS
    socket.oneror = onerrorWS
    socket.onclose = oncloseWS
    console.log('建立webSocket连接')
  } else {
    console.log('webSocket已连接')
  }
  // return socket;
}

/**
 * 打开WS之后发送心跳
 */
const onopenWS = () => {
  sendPing()
  console.log('调用了open')
  if(!window.WebSocket) {
    return
  }
  if(socket.readyState == WebSocket.OPEN) {
    let data = {
      type: REGISTER_REQUEST,
      params: {
        user_id: user_id
      }
    }
    socket.send(JSON.stringify(data))
    sendPing()
  } else {
    ElMessage({
      message: 'websocket连接没有开启',
      type: 'warning'
    })
  }
}

/**
 * 连接失败重连
 */
const onerrorWS = () => {
  socket.close()
  clearInterval(setIntervalWeSocketPush)
  console.log('连接失败重连中')
  if(socket.readyState !== 3) {
    socket = null
    createSocket()
  }
  sendPing()
}

/**
 * ws数据连接统一处理
 */
const onmessageWS = event => {
  let json = JSON.parse(event.data)
  if(json.type != 12 ) {
    console.log('收到的消息')
    console.log(json)
  }
  if(json.status === 200) {
    switch(json.type) {
      case 2:
        console.log('处理单聊')
        handleSingleMessage(json)
        
        break;
      case 4:
        console.log('处理创建群聊')
        handleCreateChatResponse(json)
        break;
      case 10: // 群聊消息接受 其实  也是适配单聊
        handleGroupMessageResponse(json)
        break;
      case 12:
        // console.log('收到心跳检测回复')
        break;
      default:
        break;
    }
  } else {
    ElMessage({
      message: '发送失败，对方不在线',
      type: 'warning'
    })
  }
  
}

/**
 * 断开重连
 */
 const oncloseWS = () => {
  clearInterval(setIntervalWeSocketPush)
  console.log('webSocket已断开....正在尝试重连')
  if(socket.readyState !== 2) {
    socket = null
    createSocket()
  }
  sendPing()
}



/**
 * 发送数据但连接未建立时进行处理等待重发
 */
const connecting = message => {
  setTimeout(() => {
    if(socket.readyState === 0) {
      connecting(message)
    } else {
      socket.send(JSON.stringify(message))
    }
  }, 1000)
}

/**
 * 发送数据
 */
export const sendWSPush = message => {
  console.log('发送的数据')
  console.log(message)
  if(socket !== null && socket.readyState === 3) {
    socket.close()
    createSocket()
  } else if(socket.readyState === 1) {
    socket.send(JSON.stringify(message))
  } else if(socket.readyState === 0) {
    connecting(message)
  }
}

// 断开websocket
export const closeConnect = () => {
  if(socket) {
    return socket
  }
}


/**
 * 发送心跳
 * @param {*} time 心跳间隔毫秒  默认5000
 */
export const sendPing = (time = 5000) => {
  console.log('调用了心跳')
  clearInterval(setIntervalWeSocketPush)
  // socket.send(ping)
  setIntervalWeSocketPush = setInterval(() => {
    if(socket.readyState == 1) {
      let data = {
        type: HEARTBEAT_REQUEST,
        params: {}
      }
      socket.send(JSON.stringify(data))
    } else {
      connecting()
    }
  }, time)
}


// 处理收到单聊的信息
const handleSingleMessage = (jsonObj) => {
  console.log('单聊收到的信息')
  console.log(jsonObj)
  let newMessage = null
  if (jsonObj.data.talk_type === 0) {
    newsMainStore.$state.chatMenu.forEach(item => {
      if(item.user_id === jsonObj.data.user_friend.user_friend_id) {
        console.log('进入了')
        console.log(item)
        newMessage = {...item}
        newMessage.msg_content = jsonObj.data.msg_content
        newMessage.msg_type = jsonObj.data.msg_type
        newMessage.talk_type = jsonObj.data.talk_type
        newMessage.msg_date = formatYMD(jsonObj.data.msg_date)
        newsMainStore.del_ChatMenu(item.user_id)
        newsMainStore.save_ChatMenu(newMessage)
      }
    })
  } else {
    newsMainStore.$state.chatMenu.forEach(item => {
      if(item.group_id === jsonObj.data.talk_id) {
        console.log('群组区域数据')
        console.log(item)
        newMessage = {...item}
        newMessage.msg_content = jsonObj.data.msg_content
        newMessage.msg_date =  formatYMD(jsonObj.data.msg_date)
        newMessage.msg_type = jsonObj.data.msg_type
        newMessage.talk_type = jsonObj.data.talk_type
        newMessage.friend_id = item.group_id
        newMessage.avatar2 = jsonObj.data.user_friend.avatar
        newMessage.nickname2 = jsonObj.data.user_friend.nickname
        newMessage.user_id2 = jsonObj.data.user_friend.user_friend_id
        newMessage.username = jsonObj.data.user_friend.username
        newsMainStore.del_ChatMenu(item.user_id)
        newsMainStore.save_ChatMenu(newMessage)
      }
    })
  }
 
  // let self = this
  // let params = {
  //   message: jsonObj.params.message,
  //   type: MESSAGE_RESPONSE,
  //   image: jsonObj.params.fileType,
  //   fileType: jsonObj.params.fileType
  // }
  // if(jsonObj.params.fileType == "1") {
  //   params.fileName = jsonObj.params.message.split("(")[0]
  // }
  // let fromUser = jsonObj.params.fromUser
  // let tOUser = jsonObj.params.tOUser
  // let exist = false
  
}
// 处理创建聊天成功返回处理
const handleCreateChatResponse = (jsonObj) => {
  console.log('创建聊天成功返回处理')
  console.log(jsonObj)
  let self = this
  let createParams = {
    messageTip: "",
    unReadCount: 0,
    userId: jsonObj.groupId,
    showName: jsonObj.nameList.toString(),
    image: 'group.jpg',
    groupId: jsonObj.groupId,
    isTop: false
  }
}
// 接受群聊信息返回处理
const handleGroupMessageResponse = (jsonObj) => {
  console.log('接受群聊信息返回==')
  console.log(jsonObj)
  let params = {
    message: jsonObj.params.message,
    type: 2,
    image: jsonObj.params.fromUser.image,
    fileType: jsonObj.params.fileType,
    showName: jsonObj.params.nameList.toString()
  }
  if(jsonObj.params.fileType === "1") {
    params.fileName = jsonObj.params.message.split("(")[0]
  }
  let fromUser = jsonObj.params.fromUser
  let groupId = jsonObj.params.groupId
  let exist = false
}

// let ws = null
// let lockReconnect = null
// let timeout = null
// let timeoutObj = null
// let serverTimeoutObj = null
// let timeoutnum = null
// let url = 'ws://152.136.188.204:9999'

// export const createSocket = () => {
//   ws = new WebSocket(url)
//   ws.onopen = onopen
//   ws.onmessage = onmessage
//   ws.onclose = onclose
//   ws.onerror = onerror
// }

// const reconnect = () => {
//   if(lockReconnect) {
//     return;
//   }
//   lockReconnect = true
//   timeoutnum && clearTimeout(timeoutnum)
//   timeoutnum = setTimeout(() => {
//     createSocket()
//     lockReconnect = false
//   }, 5000)
// }

// const reset = () => {
//   clearTimeout(timeoutObj)
//   clearTimeout(serverTimeoutObj)
//   start()
// }

// const start = () => {
//   timeoutObj && clearTimeout(timeoutObj)
//   serverTimeoutObj && clearTimeout(serverTimeoutObj)
//   timeoutObj = setTimeout(() => {
//     if(ws.readyState == 1) {
//       let data = {
//         type: HEARTBEAT_REQUEST,
//         params: {}
//       }
//       ws.send(JSON.stringify(data))
//     } else {
//       reconnect()
//     }
//     serverTimeoutObj = setTimeout(() => {
//       ws.close()
//     }, timeout)
//   }, timeout)
// }

// const onopen = () => {
//   // sendPing()
//   console.log('调用了open')
//   if(!window.WebSocket) {
//     return
//   }
//   if(ws.readyState == WebSocket.OPEN) {
//     let data = {
//       type: REGISTER_REQUEST,
//       params: {
//         user_id: user_id
//       }
//     }
//     ws.send(JSON.stringify(data))
//     start()
//   } else {
//     ElMessage({
//       message: 'websocket连接没有开启',
//       type: 'warning'
//     })
//   }
// }

// /**
//  * ws数据连接统一处理
//  */
// const onmessage = event => {
//   let json = JSON.parse(event.data)
//   console.log('收到的消息')
//   console.log(event)
//   if(json.status === 200) {
//   } else {
//     ElMessage({
//       message: '发送失败，对方不在线',
//       type: 'warning'
//     })
//   }
 
//   reset()
// }

// /**
//  * 发送数据
//  */
// export const sendWSPush = message => {
//   console.log('发送的数据')
//   console.log(message)
//   if(ws !== null && ws.readyState === 3) {
//     ws.close()
//     createSocket()
//   } else if(ws.readyState === 1) {
//     ws.send(JSON.stringify(message))
//   } else if(ws.readyState === 0) {
//     reconnect(message)
//   }
// }

// const onclose = () => {
//   reconnect()
//   // start()
// }

// const onerror = () => {
//   reconnect()
// }
